package cn.xiaohello.UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * UDP服务器端编程中接收，发送数据的实现.
 * 
 * @author XIAO
 *
 */
public class DataSocketTestServer {

	public static void main(String[] args) {
		// 构建消息缓存数组
		byte[] data = new byte[1024];
		// 构建数据包对象
		DatagramPacket packet = new DatagramPacket(data, data.length);

		int port = 80;
		DatagramSocket socket = null;
		try {
			// 创建服务器链接，监听端口
			socket = new DatagramSocket(port);
			System.out.println("服务器准备好接收数据。。。");
			// 接收数据
			socket.receive(packet);
			// 获得缓存数组中的内容
			byte[] b = packet.getData();
			System.out.println("客户机发来的数据：" + new String(b, 0, b.length));

			// 从客户机发来的数据包中获取客户机ip
			InetAddress clientAddress = packet.getAddress();
			// 获得客户端的端口号
			int clientPort = packet.getPort();
			String message = "I AM SERVER";
			b = message.getBytes();
			// 构建要发送给客户机的数据包
			packet = new DatagramPacket(b, b.length, clientAddress, clientPort);
			// 发送数据
			socket.send(packet);

		} catch (IOException e) {
			// TODO Auto-generated catch block
		} finally {
			socket.close();
		}
	}

}
